package com.xiangwei.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
































import com.xiangwei.entity.Image;
import com.xiangwei.entity.Product;
import com.xiangwei.entity.ScanRecord;
import com.xiangwei.entity.Vendor;
import com.xiangwei.service.IGodService;
import com.xiangwei.service.IImageService;
import com.xiangwei.service.IProductService;
import com.xiangwei.service.IQrcodeService;
import com.xiangwei.service.IScanrecordService;
import com.xiangwei.service.IVendorService;
import com.xiangwei.util.Common;
import com.xiangwei.util.DESUtil;
import com.xiangwei.util.DateUtils;
import com.xiangwei.util.QiniuUtil;
import com.xiangwei.view.NutrientView;


@Controller
@RequestMapping(value = "p")
public class PortalController {
	private static final Logger logger = LoggerFactory
			.getLogger(PortalController.class);
	
	@Autowired
	private IProductService productService;
	@Autowired
	private IQrcodeService qrcodeService;
	@Autowired
	private IVendorService vendorService;
	@Autowired
	private IScanrecordService scanRecordService;
	@Autowired
	private IGodService godService;
	@Resource
	private IImageService imageService;
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "i", method = RequestMethod.GET)
	public String getTemp(HttpServletRequest request,HttpSession session,Model model){
		//System.out.println("request.getQueryString()="+request.getQueryString());
		Enumeration em =session.getAttributeNames();
		while(em.hasMoreElements()){
			session.removeAttribute(em.nextElement().toString());
		}
//		获取公众号asscessToken
//		String accessToken1 = ReadPropertiesUtil.getPropertiesValue("config.properties", "accessToken");
//		String ticket = ReadPropertiesUtil.getPropertiesValue("config.properties", "ticket");
//		String appid = ReadPropertiesUtil.getPropertiesValue("config.properties", "appid");
		
		session.setAttribute("param", request.getQueryString());
		session.setAttribute("imageUrl", QiniuUtil.IMAGEURL);
		
		String strBackUrl = null;
		if(request.getQueryString() != null){
			if (request.getQueryString().equals("null")) {
				strBackUrl = "http://" + request.getServerName()+request.getContextPath()
						+ "/p/author?t=";
			}else{
				strBackUrl = "http://" + request.getServerName()+request.getContextPath()
						+ "/p/author?t=" + request.getQueryString();
				
			}			
		}else{
			strBackUrl = "http://" + request.getServerName()+request.getContextPath()
					+ "/p/author?t=";
		}
		//System.out.println(strBackUrl);
		//处理链接  进行授权
//		strBackUrl = URLEncoder.encode(strBackUrl);
//		strBackUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?"
//				+ "appid="
//				+ appid
//				+ "&redirect_uri="
//				+ strBackUrl
//				+ "&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
//		System.out.println(strBackUrl);		
		//如果为空 既游客进入
		return "redirect:" + strBackUrl;
				
	}
	
	
	/**
	 * 微信授权
	 * */
	
	@Transactional
	@RequestMapping(value = "author", method = RequestMethod.GET)
	public String Author(String code,String state,HttpSession session,Model model,
			HttpServletRequest request,String t,String s){

		int dif = 100;
		Object obj = session.getAttribute("createTime");
		if(!Common.isNullOrEmpty(obj)){
			long createTime = (long) obj;
			long endTime = System.currentTimeMillis();
			dif = (int) ((endTime - createTime)/(1000*60));
		}else{
			session.setAttribute("createTime", System.currentTimeMillis());	
			session.setMaxInactiveInterval(60*10);//session生存时间为10分钟
		}
		
		session.setAttribute("imageUrl", QiniuUtil.IMAGEURL);

		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/uploadVideo/";
		model.addAttribute("videoUrl", basePath);
		

		
		if (t!=null && !t.equals("") && !t.equals("null")) {
			//解析二维码参数
			Map<String,Object> qrmap = getResultObject(t);
			if(Common.isNullOrEmpty(qrmap)){
				logger.error("二维码参数解析错误");
				return null;
			}
			String productId = (String) qrmap.get("productId");
			long id= Long.parseLong(qrmap.get("qrcodeId").toString());
			String str2 = productId;
			int length = 4-str2.length();
			for (int k = 0; k < length; k++) {
				str2 = "0"+str2;
			}
			
			String id1 = id+"";
			length = 8-id1.length();
			for (int k = 0; k < length; k++) {
				id1 = "0"+id1;
			}
			

			model.addAttribute("code", str2+id1);
			
			Image img= new Image();
			img.setPid(Integer.parseInt(productId));
			img.setType(Short.parseShort("1"));
			List<Image> imgList = imageService.getImagesByPidAndType(img);
			model.addAttribute("imgList", imgList);
			
			//查询产品信息
			Product p = productService.selectByPrimaryKey(Integer.parseInt(productId));
			if(Common.isNullOrEmpty(p)){
				logger.error("产品信息不存在");
				return null;//产品信息不存在
			}	
			model.addAttribute("product", p);
			model.addAttribute("vendorId", p.getVId());
			SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.PATTEN_HMS);
			String[] date = sdf.format(p.getProduceDate()).split(" ");
			model.addAttribute("date", date[0]);
			model.addAttribute("time", date[1]);
			Vendor vendor = vendorService.selectByPrimaryKey(p.getVId());
			model.addAttribute("vendorName", vendor.getVName());
			//查找产品信息,拆分营养成分，拆分配料		
			List<NutrientView> nvList = new ArrayList<NutrientView>();
			List<String> dosinglist = new ArrayList<String>();//配料
			String dosing = p.getDosing();
			if(Common.isEmptyString(dosing)){
				String[] str = dosing.split(",");
				for(int i=0;i<str.length;i++){
					dosinglist.add(str[i]);
				}
				model.addAttribute("dosinglist", dosinglist);
			}
			
			String nutrient = p.getNutrient();

			if(Common.isEmptyString(nutrient)){//营养成分是否为空；eg:糖/20g/10%,水/100g/40%
				String[] str = nutrient.split(",");//不为空拆分
				for(int i=0;i<str.length;i++){
					if(Common.isEmptyString(str[i])){
						String[] str1 = str[i].split("/");

						if(str1.length < 3){//拆分后字段值不足3
							continue;
						}
						NutrientView nv = new NutrientView();
						nv.setName(str1[0]);
						nv.setQuantity(str1[1]);
						nv.setContent(str1[2]);
						
						nvList.add(nv);												
					}
				}
				model.addAttribute("nvList", nvList);
			}
			
			
			
			//插入|更新扫码记录
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("productId",productId);
			map.put("qrcodeId",id);
			map.put("scanTime",new Date());
			boolean flg = qrcodeService.qrcodeIsExist(qrmap);
			if(flg){//判断该二维码是否存在
				ScanRecord sr = scanRecordService.selectByOpenid(productId,qrmap.get("qrcodeId").toString());
					
				if( !Common.isNullOrEmpty(sr) ){//用户已扫过该二维码	
					if(dif > 5){//5分钟内刷新页面不增加扫码记录
						int scancount = sr.getScanCount()==null?0:sr.getScanCount();
						map.put("scanCount",scancount+1);
						map.put("id", sr.getId());
					
						if(scanRecordService.updateRecord(map) <=0){
							logger.error("更新扫码记录失败");
						}else{
							logger.info("更新扫码记录成功");
						}						
					}
					model.addAttribute("scanTime", sr.getScanTime());
				}else{//未扫码
					map.put("scanCount",1);
					if(scanRecordService.insertScanrecord(map) <= 0){
						logger.error("插入扫码记录失败");
					}else{
						logger.info("插入扫码记录成功");
					}
				}															
				
				ScanRecord sr1 = scanRecordService.findRecordByScantime(productId, qrmap.get("qrcodeId").toString());
				int count = scanRecordService.findScanCountByQrcode(productId, qrmap.get("qrcodeId").toString());
				model.addAttribute("scanCount", count);
				model.addAttribute("scanRecord", sr1);
			}
			
			return "template/portal_1/index";
		}
		return null;
	}
	
	/**
	 * 厂商信息展示
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="showVendor",method=RequestMethod.GET)
	public String showVendor(String id,Model model,HttpSession session){
		if( !Common.isEmptyString(id) ){
			logger.error("method showVendor 传入参数为空");
			return null;
		}
		Image img= new Image();
		img.setPid(Integer.parseInt(id));
		img.setType(Short.parseShort("0"));
		List<Image> imgList = imageService.getImagesByPidAndType(img);
		model.addAttribute("imgList", imgList);
		session.setAttribute("imageUrl", QiniuUtil.IMAGEURL);
		Vendor vendor = vendorService.selectByPrimaryKey(Integer.parseInt(id));
		model.addAttribute("vendor", vendor);
		return "template/portal_1/vendor";
	}
	
	
	
	

	
	/**
	 * 解析二维码参数 返回Map<String,Object>
	 * */
	private static Map<String,Object> getResultObject(String t){
		//System.out.println(t);
		Map<String,Object> map = new HashMap<String, Object>();
		DESUtil des = new DESUtil("xiangwei");
		t = t.replaceAll(" ", "+"); // 对于+这个字符获取后为空格，所以将其替换
		String[] str = t.split("&");
		if(str.length >= 1){
			String productId=str[0].substring(0,4).replaceAll("^(0+)", "");
			String qrcodeId =des.decryptStr(str[0].substring(4));
			map.put("productId", productId);
			map.put("qrcodeId", qrcodeId);
		}else{
			return null;
		}
		return map;
	}
	

}
